<!--商品信息页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">商品信息管理</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="beforeAddGoods">新增商品</el-button>
  </div>
  <!-- 新增商品弹窗 -->
  <el-dialog  v-model="dialogVisible" style="width:1000px;padding:40px;"
             :before-close="handleClose"
             :title="dialogTitle">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label for="name">商品名称<span class="required">*</span>
            <el-input placeholder="请输入" v-model="saveGoodsForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label for="type">商品类型<span class="required">*</span>
            <el-select placeholder="请选择" v-model="saveGoodsForm.type">
              <el-option label="食品" value="食品"></el-option>
              <el-option label="生活用品" value="生活用品"></el-option>
              <el-option label="特殊服务" value="特殊服务"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label for="price" >商品价格<span class="required">*</span>
            <el-input placeholder="请输入商品价格" v-model="saveGoodsForm.price"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label for="repertory">商品库存<span class="required">*</span>
            <el-input placeholder="请输入商品库存数" v-model="saveGoodsForm.repertory"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品编码">
            <el-input placeholder="请输入商品编码" v-model="saveGoodsForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品状态">
            <el-select placeholder="请选择" v-model="saveGoodsForm.status">
              <el-option label="在售" value="在售"></el-option>
              <el-option label="下架" value="下架"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品销量">
            <el-input placeholder="请输入商品销量" v-model="saveGoodsForm.sales"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item lab
                        el for="picture">商品图片<span class="required">*</span>
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPrevie"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibl">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveGoods">确定</el-button>
    </template>
  </el-dialog>

  <!-- 商品 搜索卡片 -->
  <el-card style="margin: 20px;">
    <el-form style="padding-top:10px;">
      <el-row :gutter="30">
        <el-col :span="4">
          <el-form-item label="商品名称">
            <el-input placeholder="请输入关键字" v-model="searchGoodsForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="编码">
            <el-input placeholder="请输入您所需商品编码" v-model="searchGoodsForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上架时间">
            <el-date-picker type="date" format="YYYY-MM-DD" v-model="searchGoodsForm.updateTime"
                            value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态">
            <el-select placeholder="请选择" v-model="searchGoodsForm.status">
              <el-option label="在售" value="在售"></el-option>
              <el-option label="已下架" value="已下架"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="success" @click="loadGoods"><el-icon><Search /></el-icon></el-button>
            <el-button><el-icon @click="resetSearch"><RefreshRight /></el-icon></el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
<!--商品界面信息-->
  <el-card style="margin:20px">
    <el-radio-group style="margin-bottom: 15px;" v-model="searchGoodsForm.type" @change="loadGoods">
      <el-radio-button value="食品" size="large">食品</el-radio-button>
      <el-radio-button value="生活用品" size="large">生活用品</el-radio-button>
      <el-radio-button value="特殊服务" size="large">特殊服务</el-radio-button>
    </el-radio-group>
    <el-table :data="goodsArr">
      <el-table-column type="index" width="80" align="center" prop="id" label="编号"></el-table-column>
      <el-table-column align="center" prop="name" label="商品名称"></el-table-column>
      <el-table-column align="center" prop="picture" label="商品图片">
          <template #default="scope">
            <img :src="scope.row.picture" style="width: 120px; height: 100px;">
          </template>
      </el-table-column>
      <el-table-column align="center" prop="code" label="商品编码"></el-table-column>
      <el-table-column align="center" prop="type" label="分类"></el-table-column>
      <el-table-column align="center" prop="price" label="价格"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="scope">
          <!--  scope.row就代表表格中当前行的用户对象,也就是后端返回的userVO -->
          <el-switch active-value="在售" inactive-value="下架"
                     v-model="scope.row.status"
                     @change="changeStatus(scope.row.id,scope.row.status)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="sales" label="销量"></el-table-column>
      <el-table-column align="center" prop="repertory" label="库存"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
      <el-table-column align="center" prop="updateTime" label="最后更新时间"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope" >
          <div style="display: flex; justify-content: center; align-items: center; padding: 0;">
          <el-button type="primary"  id="copyButton" size="small" link @click="showGoods(scope.row.id)"><el-icon size="20px"><CopyDocument /></el-icon></el-button>
          <el-button type="primary" size="small" link @click="editGoods(scope.row.id)"><el-icon size="20px"><Edit /></el-icon></el-button>
          <el-button type="danger" size="small"  link @click="deleteGoods(scope.row.id)"><el-icon size="20px"><Delete /></el-icon></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from '@/util/request';
import qs from "qs";
import {ElMessage} from "element-plus";
//定义变量控制新建商品弹窗是否出现
const dialogVisible = ref(false);
//控制新增商品弹窗是否显示
const dialogGoods = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('新增商品');
//获取当前登录的用户信息
const user = ref(getUser());
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
//定义对象用来保存商品弹窗表单数据
const saveGoodsForm = ref({
  name:'',
  code:'',
  type:'',
  price:'',
  status:'',
  repertory:'',
  createTime:'',
  updateTime:'',
  picture:'',
sales:''
})
//定义数组用来保存新增申请单时,对应审批人的用户id,入库使用
const auditUserIdList = ref([]);

//7.定义获取当前登录对象数据的全局方法
  window.getGoods = ()=>{
    //如果获取到了用户数据,则转回JS对象
    //如果没有获取到用户数据,转为布尔是false,值为null
    return localStorage.user ? JSON.parse(localStorage.user) : null;
  }

//获取当前登录的用户信息
const goods = ref(getGoods());
const saveGoods = ()=>{
  if(fileList.value.length==0){
    ElMessage.error('请填写商品名称');
    return;
  }
  // //从upload图片上传组件中获取上传图片的路径 fileList.value[0]是第一个图片对象
  saveGoodsForm.value.picture = fileList.value[0].response.data;
  console.log(fileList)
  /*注意:审批人id集合是需要一起给到后端的,因为事务性新增,审批表的数据也需要一起新增!*/
  saveGoodsForm.value.auditUserIdList = auditUserIdList.value;
  console.log(saveGoodsForm.value);
  let data = qs.stringify(saveGoodsForm.value);

  axios.post('/v1/goods/save',data).then((response)=>{
    if(response.data.code == 2000){
      // if(saveGoodsForm.value.picture){
      //   fileList.value.push({url:saveGoodsForm.value.picture})
      // }
      ElMessage.success('保存成功!');
      dialogVisible.value = false;
      loadGoods();
      // addApplicationDialogVisible.value = false;//关闭弹窗
      goods.value = [];//清空日期时间选择器中的数据
      fileList.value = [];//清空图片上传组件的数据
      saveGoodsForm.value = {};//其他项清空
      //新增申请单后,需要重新加载所有的申请数据!!!
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//点击“新增车辆”按钮：显示弹窗并设置标题
const beforeAddGoods = ()=>{
  dialogTitle.value = '新增商品信息';
  dialogVisible.value = true;
}
//定义处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭弹窗吗?')){
    saveGoodsForm.value = {};
    dialogVisible.value = false;
  }
}
//一进到页面立即加载全部车辆
onMounted(()=>{
  loadGoods();
})
// 删除商品
const deleteGoods = (id)=>{
  if(confirm('是否确认要删除本商品?')){
    axios.post('/v1/goods/delete/'+id).then((response)=>{
      if(response.data.code == 2000){
        ElMessage.success('删除成功!');
        loadGoods();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}
//定义对象用来保存商品的查询条件
const searchGoodsForm = ref({name:'',code:'',status:'',updateTime:'',type:'',sales:'',picture:''});
const goodsArr = ref([]);
//定义加载商品的方法
const loadGoods = ()=>{
  let data = qs.stringify(searchGoodsForm.value);
  axios.get('/v1/goods/select?'+data).then((response)=>{
    if(response.data.code == 2000){
      goodsArr.value = response.data.data.map(goods => ({
        ...goods,
        picture: BASE_URL + goods.picture // 拼接完整的 URL
        }))
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//定义重置搜索的方法
const resetSearch = ()=>{
  searchGoodsForm.value = {};
  loadGoods();
}
//定义编辑车辆的方法
const editGoods = (id)=>{
  //1.修改弹窗标题并让弹窗出现
  dialogTitle.value = '编辑商品信息';
  dialogVisible.value = true;
  //2.给后端发请求，获取当前商品的详细数据
  axios.get('/v1/goods/select?id='+id).then((response)=>{
    if (saveGoodsForm.value.picture){
      fileList.value.push({url:BASE_URL + saveGoodsForm.value.picture})
    }
    if(response.data.code == 2000){
      //3.将数据赋值给表单对象
      saveGoodsForm.value = response.data.data[0];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
// 在售和上架开关
const value1 = ref(true)
//修改状态
const changeStatus = (goodsId,status)=>{
  axios.post('/v1/goods/update/status/'+goodsId+'/'+status)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('修改状态成功!');
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
  // Get the current page URL
  const pageUrl = window.location.href;

  // Create a temporary textarea element to hold the URL
  const tempTextArea = document.createElement('textarea');
  tempTextArea.value = pageUrl;

  // Append the textarea to the body temporarily
  document.body.appendChild(tempTextArea);

  // Select the text content in the textarea
  tempTextArea.select();
  tempTextArea.setSelectionRange(0, 99999); // For mobile devices

  // Copy the text to clipboard
  document.execCommand('copy');

  // Remove the temporary textarea element
  document.body.removeChild(tempTextArea);

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisibl = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPrevie = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisibl.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
</script>

<style scoped>
.required {
  color: red;
  font-weight: bold; /* 可选：使星号更突出 */
  margin-left: 1px;  /* 可选：为星号添加一些左边距 */
}
</style>